import { login, profile, getUserDatailById } from '../../api/user'
const state = {
  token: localStorage.getItem('token') || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    localStorage.setItem('token', data)
    state.token = data
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeToken(state) {
    localStorage.removeItem('token')
    state.token = ''
  },
  removeuserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(state, data) {
    const res = await login(data)
    console.log(res)
    state.commit('setToken', res)
    localStorage.setItem('TiemTokne', Date.now())
  },
  async getUserInfo(store) {
    const res = await profile()
    const detail = await getUserDatailById(res.userId)
    store.commit('setUserInfo', {
      ...res,
      ...detail
    })
  },
  async logout(store) {
    store.commit('removeToken')
    store.commit('removeuserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
